package org.zn.note.mybatis.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @ClassName DbUtils
 * @Author zn
 * @Date 2020/3/12 17:09
 **/
public class DbUtils {

    private final static String DBCONFIG = "/db.properties";
    private final static Properties CONFIG = new Properties();

    static {
        try (InputStream in = DbUtils.class.getResourceAsStream(DBCONFIG)) {
            CONFIG.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection newConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(get("url"), get("username"), get("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static boolean testConnection(Connection conn) {
        boolean result = false;
        try (Statement stat = conn.createStatement()) { // AutoCloseable
            ResultSet resultSet = stat.executeQuery("select 1 from dual");
            if (resultSet.next())
                result = (resultSet.getInt(1) == 1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    private static String get(String s) {
        return (String) CONFIG.get(s);
    }

    /**
     * 测试JDBC缓存
     */
    private static void testJdbcCache() {
        try (Connection connection = newConnection()) {

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SQLException {
        Connection connection = newConnection();
        System.out.println(testConnection(connection));
        connection.close();
    }
}